package com.xiaomaoguai.fcp;

import cn.hutool.core.io.IoUtil;
import com.dh.conf.ZkClientProvider;
import org.I0Itec.zkclient.ZkClient;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.junit.After;
import org.junit.Before;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.nio.channels.FileChannel;
import java.util.List;

/**
 * @fileName: AbstractZkTool.java
 * @author: WeiHui
 * @date: 2018/11/23 10:06
 * @version: v1.0.0
 * @since JDK 1.8
 */
public abstract class AbstractZkTool {

	public static final String rootNode = "/plouto/convert";

	private static final String zkServers = "10.139.103.1:2181";

	protected String node;

	protected ZkClient client;

	abstract String setUpYourLocalPath();

	@Before
	public void before() {
		this.client = ZkClientProvider.getClient(zkServers, 5000);
	}

	@After
	public void writeData() {
		if (StringUtils.isNotBlank(node)) {
			writeData(node);
		}
	}

	protected void createZkNode(String node) {
		if (!client.exists(node)) {
			client.createPersistent(node, true);
		}
	}

	protected String readContent(String fileName) {
		String content = null;
		FileInputStream fileInputStream;
		FileChannel fileChannelInput = null;
		try {
			fileInputStream = new FileInputStream(new File(setUpYourLocalPath() + fileName));
			fileChannelInput = fileInputStream.getChannel();
			content = IoUtil.readUtf8(fileChannelInput);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} finally {
			IoUtil.close(fileChannelInput);
			IoUtil.close(fileChannelInput);
		}
		return content;
	}

	protected void writeData(String node) {
		try {
			String fileName = StringUtils.substringAfterLast(node, "/") + ".json";
			client.writeData(node, readContent(fileName));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	protected void downZKAll() {
		try {
			List<String> children = client.getChildren(rootNode);
			for (String child : children) {
				String content = client.readData(rootNode + "/" + child);
				File file = new File(setUpYourLocalPath() + child + ".json");
				if (!file.exists()) {
					FileUtils.touch(file);
					FileUtils.write(file, content, "UTF-8");
				}
			}
			autoOpen();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	protected void downOne(String node) {
		try {
			String content = client.readData(rootNode + "/" + node);
			File file = new File(setUpYourLocalPath() + node + ".json");
			if (!file.exists()) {
				FileUtils.touch(file);
				FileUtils.write(file, content, "UTF-8");
			}
			autoOpen();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	protected void autoOpen() throws Exception {
		Runtime.getRuntime().exec("cmd /c start " + setUpYourLocalPath());
	}
}
